<template>
  <view class="statistics-page">
    <!-- 导航栏 -->
    <u-navbar title="统计报表" back-icon="arrow-left" />
    
    <!-- 时间筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <u-input
          v-model="filterForm.startDate"
          placeholder="开始日期"
          readonly
          @click="showStartDatePicker = true"
          class="filter-input"
        />
        <text class="filter-separator">至</text>
        <u-input
          v-model="filterForm.endDate"
          placeholder="结束日期"
          readonly
          @click="showEndDatePicker = true"
          class="filter-input"
        />
        <u-button 
          type="primary" 
          text="查询" 
          size="mini"
          @click="handleQuery"
        />
      </view>
    </view>

    <!-- 统计卡片区域 -->
    <view class="statistics-section">
      <view class="statistics-card">
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.totalTasks || 0 }}</text>
          <text class="statistics-label">总任务数</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.completedTasks || 0 }}</text>
          <text class="statistics-label">已完成</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.pendingTasks || 0 }}</text>
          <text class="statistics-label">待处理</text>
        </view>
        <view class="statistics-item">
          <text class="statistics-value">{{ statistics.averageScore || 0 }}</text>
          <text class="statistics-label">平均评分</text>
        </view>
      </view>
    </view>

    <!-- 图表区域 -->
    <view class="chart-section">
      <view class="section-title">任务完成情况</view>
      <view class="chart-container">
        <view class="chart-item">
          <text class="chart-label">已完成</text>
          <view class="chart-bar">
            <view 
              class="chart-fill success"
              :style="{ width: getCompletionPercentage() + '%' }"
            ></view>
          </view>
          <text class="chart-value">{{ statistics.completedTasks || 0 }}</text>
        </view>
        <view class="chart-item">
          <text class="chart-label">进行中</text>
          <view class="chart-bar">
            <view 
              class="chart-fill warning"
              :style="{ width: getInProgressPercentage() + '%' }"
            ></view>
          </view>
          <text class="chart-value">{{ statistics.inProgressTasks || 0 }}</text>
        </view>
        <view class="chart-item">
          <text class="chart-label">待分配</text>
          <view class="chart-bar">
            <view 
              class="chart-fill info"
              :style="{ width: getUnassignedPercentage() + '%' }"
            ></view>
          </view>
          <text class="chart-value">{{ statistics.unassignedTasks || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 质量评分区域 -->
    <view class="quality-section">
      <view class="section-title">质量评分分布</view>
      <view class="quality-container">
        <view class="quality-item">
          <text class="quality-label">优秀 (9-10分)</text>
          <view class="quality-bar">
            <view 
              class="quality-fill excellent"
              :style="{ width: getQualityPercentage('excellent') + '%' }"
            ></view>
          </view>
          <text class="quality-value">{{ qualityStats.excellent || 0 }}</text>
        </view>
        <view class="quality-item">
          <text class="quality-label">良好 (7-8分)</text>
          <view class="quality-bar">
            <view 
              class="quality-fill good"
              :style="{ width: getQualityPercentage('good') + '%' }"
            ></view>
          </view>
          <text class="quality-value">{{ qualityStats.good || 0 }}</text>
        </view>
        <view class="quality-item">
          <text class="quality-label">一般 (5-6分)</text>
          <view class="quality-bar">
            <view 
              class="quality-fill average"
              :style="{ width: getQualityPercentage('average') + '%' }"
            ></view>
          </view>
          <text class="quality-value">{{ qualityStats.average || 0 }}</text>
        </view>
        <view class="quality-item">
          <text class="quality-label">较差 (1-4分)</text>
          <view class="quality-bar">
            <view 
              class="quality-fill poor"
              :style="{ width: getQualityPercentage('poor') + '%' }"
            ></view>
          </view>
          <text class="quality-value">{{ qualityStats.poor || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 人员统计区域 -->
    <view class="staff-section">
      <view class="section-title">人员工作统计</view>
      <view class="staff-list">
        <view 
          v-for="staff in staffStats" 
          :key="staff.userId"
          class="staff-item"
        >
          <view class="staff-info">
            <text class="staff-name">{{ staff.userName }}</text>
            <text class="staff-tasks">完成任务：{{ staff.completedTasks }}个</text>
          </view>
          <view class="staff-progress">
            <view class="progress-bar">
              <view 
                class="progress-fill"
                :style="{ width: staff.completionRate + '%' }"
              ></view>
            </view>
            <text class="progress-text">{{ staff.completionRate }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showStartDatePicker"
      v-model="startDateValue"
      mode="date"
      @confirm="onStartDateConfirm"
      @cancel="showStartDatePicker = false"
      title="选择开始日期"
    />
    
    <u-datetime-picker
      :show="showEndDatePicker"
      v-model="endDateValue"
      mode="date"
      @confirm="onEndDateConfirm"
      @cancel="showEndDatePicker = false"
      title="选择结束日期"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getCleaningStatistics } from '@/api/cleaning'

// 响应式数据
const statistics = ref({})
const qualityStats = ref({})
const staffStats = ref([])
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  startDate: '',
  endDate: ''
})

// 选择器显示状态
const showStartDatePicker = ref(false)
const showEndDatePicker = ref(false)

// 日期值
const startDateValue = ref('')
const endDateValue = ref('')

// 页面加载时获取数据
onMounted(() => {
  // 设置默认日期范围（最近30天）
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  filterForm.startDate = formatDate(startDate)
  filterForm.endDate = formatDate(endDate)
  
  loadStatistics()
})

/**
 * 加载统计信息
 */
const loadStatistics = async () => {
  try {
    loading.value = true
    const response = await getCleaningStatistics(filterForm.startDate, filterForm.endDate)
    if (response.success && response.data) {
      statistics.value = response.data
      // 模拟质量统计数据
      qualityStats.value = {
        excellent: Math.floor((statistics.value.completedTasks || 0) * 0.3),
        good: Math.floor((statistics.value.completedTasks || 0) * 0.4),
        average: Math.floor((statistics.value.completedTasks || 0) * 0.2),
        poor: Math.floor((statistics.value.completedTasks || 0) * 0.1)
      }
      // 模拟人员统计数据
      staffStats.value = [
        { userId: 1, userName: '张三', completedTasks: 15, completionRate: 85 },
        { userId: 2, userName: '李四', completedTasks: 12, completionRate: 75 },
        { userId: 3, userName: '王五', completedTasks: 18, completionRate: 90 }
      ]
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
    uni.showToast({
      title: '加载统计信息失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

/**
 * 查询处理
 */
const handleQuery = () => {
  loadStatistics()
}

/**
 * 开始日期确认
 */
const onStartDateConfirm = (event) => {
  filterForm.startDate = formatDate(new Date(event.value))
  showStartDatePicker.value = false
}

/**
 * 结束日期确认
 */
const onEndDateConfirm = (event) => {
  filterForm.endDate = formatDate(new Date(event.value))
  showEndDatePicker.value = false
}

/**
 * 格式化日期
 */
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

/**
 * 获取完成率百分比
 */
const getCompletionPercentage = () => {
  const total = statistics.value.totalTasks || 0
  const completed = statistics.value.completedTasks || 0
  return total > 0 ? Math.round((completed / total) * 100) : 0
}

/**
 * 获取进行中百分比
 */
const getInProgressPercentage = () => {
  const total = statistics.value.totalTasks || 0
  const inProgress = statistics.value.inProgressTasks || 0
  return total > 0 ? Math.round((inProgress / total) * 100) : 0
}

/**
 * 获取待分配百分比
 */
const getUnassignedPercentage = () => {
  const total = statistics.value.totalTasks || 0
  const unassigned = statistics.value.unassignedTasks || 0
  return total > 0 ? Math.round((unassigned / total) * 100) : 0
}

/**
 * 获取质量评分百分比
 */
const getQualityPercentage = (level) => {
  const total = statistics.value.completedTasks || 0
  const count = qualityStats.value[level] || 0
  return total > 0 ? Math.round((count / total) * 100) : 0
}
</script>

<style lang="scss" scoped>
.statistics-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.filter-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .filter-row {
    display: flex;
    align-items: center;
    gap: 16rpx;
    
    .filter-input {
      flex: 1;
    }
    
    .filter-separator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.statistics-section {
  padding: 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .statistics-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    
    .statistics-item {
      text-align: center;
      
      .statistics-value {
        display: block;
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .statistics-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.chart-section, .quality-section, .staff-section {
  padding: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.chart-container {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .chart-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .chart-label {
      width: 120rpx;
      font-size: 26rpx;
      color: #666;
    }
    
    .chart-bar {
      flex: 1;
      height: 16rpx;
      background: #f0f0f0;
      border-radius: 8rpx;
      margin: 0 20rpx;
      overflow: hidden;
      
      .chart-fill {
        height: 100%;
        border-radius: 8rpx;
        transition: width 0.3s ease;
        
        &.success {
          background: #2ed573;
        }
        
        &.warning {
          background: #ffa502;
        }
        
        &.info {
          background: #3498db;
        }
      }
    }
    
    .chart-value {
      width: 80rpx;
      text-align: right;
      font-size: 26rpx;
      color: #333;
      font-weight: 600;
    }
  }
}

.quality-container {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .quality-item {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .quality-label {
      width: 160rpx;
      font-size: 26rpx;
      color: #666;
    }
    
    .quality-bar {
      flex: 1;
      height: 16rpx;
      background: #f0f0f0;
      border-radius: 8rpx;
      margin: 0 20rpx;
      overflow: hidden;
      
      .quality-fill {
        height: 100%;
        border-radius: 8rpx;
        transition: width 0.3s ease;
        
        &.excellent {
          background: #2ed573;
        }
        
        &.good {
          background: #7bed9f;
        }
        
        &.average {
          background: #ffa502;
        }
        
        &.poor {
          background: #ff4757;
        }
      }
    }
    
    .quality-value {
      width: 80rpx;
      text-align: right;
      font-size: 26rpx;
      color: #333;
      font-weight: 600;
    }
  }
}

.staff-list {
  .staff-item {
    background: white;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .staff-info {
      margin-bottom: 16rpx;
      
      .staff-name {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .staff-tasks {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .staff-progress {
      display: flex;
      align-items: center;
      
      .progress-bar {
        flex: 1;
        height: 12rpx;
        background: #f0f0f0;
        border-radius: 6rpx;
        margin-right: 16rpx;
        overflow: hidden;
        
        .progress-fill {
          height: 100%;
          background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
          border-radius: 6rpx;
          transition: width 0.3s ease;
        }
      }
      
      .progress-text {
        font-size: 24rpx;
        color: #333;
        font-weight: 600;
        min-width: 80rpx;
        text-align: right;
      }
    }
  }
}
</style>
